package com.program.houai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.program.houai.entity.BankCardEntity;
import com.program.houai.entity.UserBankCardEntity;
import com.program.houai.entity.UserEntity;
import com.program.houai.entity.UserWithdrawEntity;
import com.program.houai.exception.BusinessException;
import com.program.houai.exception.ErrorType;
import com.program.houai.po.LoginUser;
import com.program.houai.redis.RedisService;
import com.program.houai.service.*;
import com.program.houai.util.PageUtils;
import com.program.houai.util.PageVO;
import com.program.houai.util.R;
import com.program.houai.vo.BaseVO;
import com.program.houai.vo.OrderQUeryVO;
import com.program.houai.vo.UserPackVO;
import com.program.houai.vo.UserWithdrawVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version v1.0
 * @ProjectName: hou
 * @ClassName: BankCardController
 * @Description: TODO(一句话描述该类的功能)
 * @Author: Topcheer
 * @Date: 2024/9/6 21:26
 */
@Api(tags = "银行卡接口")
@RestController
@RequestMapping("/app/card")
@Slf4j
@Validated
public class BankCardController {

    @Autowired
    private IUserBankCardService userBankCardService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IUserWithdrawService userWithdrawService;

    @Autowired
    private IGenerateOrderNumberService generateOrderNumberService;

    @Autowired
    private IUserService userService;

    @Value("${system.file.request-url}")
    private String requestUrl;

    @Autowired
    private IBankCardService bankCardService;

    @ApiOperation("我的银行卡列表")
    @PostMapping(value = "/userCardList", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<PageUtils<UserBankCardEntity>> userCardList(@RequestBody PageVO pageVO, @RequestHeader("token") String token) {
        LoginUser loginUser = redisService.getLoginValueByToken(token);
        QueryWrapper<UserBankCardEntity> userWrap = new QueryWrapper<UserBankCardEntity>();
        userWrap.eq("user_id", loginUser.getId());
        userWrap.orderByDesc("id");
        IPage<UserBankCardEntity> page = new Page<>(pageVO.getPageNum(), pageVO.getPageSize());
        page = userBankCardService.getBaseMapper().selectPage(page, userWrap);

        List<BankCardEntity> bankCardEntityList =  bankCardService.list();
        Map<String,String> carMap = new HashMap<>();
        for (BankCardEntity bankCardEntity : bankCardEntityList){
            carMap.put(bankCardEntity.getBankCode(),bankCardEntity.getBankName());
        }
        for (UserBankCardEntity userBankCardEntity :page.getRecords()){
            userBankCardEntity.setBankUrl(requestUrl+"static/bank/"+userBankCardEntity.getBankDeposit()+".png");
            userBankCardEntity.setBankLogoUrl(requestUrl+"static/bank/logo/"+userBankCardEntity.getBankDeposit()+".png");
            userBankCardEntity.setBankDeposit(carMap.get(userBankCardEntity.getBankDeposit()));
            String bankNumber = userBankCardEntity.getBankNumber().substring(userBankCardEntity.getBankNumber().length()-4,userBankCardEntity.getBankNumber().length());
            userBankCardEntity.setBankNumber(bankNumber);
        }
        return R.ok(new PageUtils<>(page));
    }

    @ApiOperation("添加或者修改银行卡 不传Id是新增，传Id是修改")
    @PostMapping(value = "/saveOrUpdateUserCard", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Boolean> saveOrUpdateUserCard(@RequestBody UserBankCardEntity userBankCardEntity, @RequestHeader("token") String token) {
        LoginUser loginUser = redisService.getLoginValueByToken(token);
        userBankCardEntity.setUserId(loginUser.getId());
        boolean result  = userBankCardService.saveOrUpdate(userBankCardEntity);
        return R.ok(result);
    }

    @ApiOperation("侧滑删除我绑定的卡")
    @PostMapping(value = "/delUserCard", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Boolean> delUserCard(@RequestBody BaseVO baseVO) {
        boolean result  = userBankCardService.removeById(baseVO.getId());
        return R.ok(result);
    }

    @ApiOperation("用户提现记录")
    @PostMapping(value = "/userWithdrawList", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<PageUtils<UserWithdrawEntity>> userWithdrawList(@RequestBody PageVO pageVO, @RequestHeader("token") String token) {
        LoginUser loginUser = redisService.getLoginValueByToken(token);
        QueryWrapper<UserWithdrawEntity> userWrap = new QueryWrapper<UserWithdrawEntity>();
        userWrap.eq("user_id", loginUser.getId());
        userWrap.eq("type", 2);
        userWrap.orderByDesc("id");

        List<BankCardEntity> bankCardEntityList =  bankCardService.list();
        Map<String,String> carMap = new HashMap<>();
        for (BankCardEntity bankCardEntity : bankCardEntityList){
            carMap.put(bankCardEntity.getBankCode(),bankCardEntity.getBankName());
        }

        IPage<UserWithdrawEntity> page = new Page<>(pageVO.getPageNum(), pageVO.getPageSize());
        page = userWithdrawService.getBaseMapper().selectPage(page, userWrap);
        for (UserWithdrawEntity userWithdrawEntity :page.getRecords()){
            BigDecimal divisor = BigDecimal.valueOf(100);
            BigDecimal dividend = BigDecimal.valueOf( userWithdrawEntity.getBalance());
            BigDecimal price = dividend.divide(divisor, 2, RoundingMode.HALF_UP);
            userWithdrawEntity.setBalanceStr(price.toString());

            BigDecimal dividend1 = BigDecimal.valueOf( userWithdrawEntity.getServiceCharge());
            BigDecimal price1 = dividend1.divide(divisor, 2, RoundingMode.HALF_UP);
            userWithdrawEntity.setServiceChargeStr(price1.toString());

            BigDecimal dividend2 = BigDecimal.valueOf( userWithdrawEntity.getWithdrawAmount());
            BigDecimal price2 = dividend2.divide(divisor, 2, RoundingMode.HALF_UP);
            userWithdrawEntity.setWithdrawAmountStr("-"+price2.toString());
            userWithdrawEntity.setBankDeposit(carMap.get(userWithdrawEntity.getBankDeposit()));

        }
        return R.ok(new PageUtils<>(page));
    }

    @ApiOperation("用户发起提现")
    @PostMapping(value = "/saveUserWithdraw", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<String> saveUserWithdraw(@RequestBody UserWithdrawVO userWithdrawVO, @RequestHeader("token") String token){

        LoginUser loginUser = redisService.getLoginValueByToken(token);

        String orderNumber =  generateOrderNumberService.generateOrderNumber();
        UserWithdrawEntity  userWithdrawEntity = new UserWithdrawEntity();
        userWithdrawEntity.setCardId(userWithdrawVO.getCardId());
        userWithdrawEntity.setCreateTime(new Date());
        userWithdrawEntity.setWithdrawNumber(orderNumber);

        UserBankCardEntity userBankCardEntity = userBankCardService.getById(userWithdrawVO.getCardId());
        userWithdrawEntity.setIdCard(userBankCardEntity.getIdCard());
        userWithdrawEntity.setIsCheck(0);
        userWithdrawEntity.setBankNumber(userBankCardEntity.getBankNumber());
        userWithdrawEntity.setBankBranch(userBankCardEntity.getBankBranch());
        userWithdrawEntity.setBankDeposit(userBankCardEntity.getBankDeposit());
        userWithdrawEntity.setName(userBankCardEntity.getName());
        userWithdrawEntity.setUserId(loginUser.getId());
        userWithdrawEntity.setType(2);
        //提现金额
        int curryMount = (int) (userWithdrawVO.getWithdraw()*100);
        UserEntity userEntity = userService.getById(loginUser.getId());
        if (userEntity.getMoney() < curryMount){
            throw new BusinessException(ErrorType.BIZ_ERROR,"提现余额不足！");
        }
        int ye = userEntity.getMoney() - curryMount;
        int result = userService.updateUserMoney(loginUser.getId(),userEntity.getMoney(),ye);
        if (result > 0){
            //钱包当前余额
            userWithdrawEntity.setBalance(ye);
            //服务费
            userWithdrawEntity.setServiceCharge(0);
            //提现金额
            userWithdrawEntity.setWithdrawAmount(curryMount);
        }else{
            throw new BusinessException(ErrorType.BIZ_ERROR,"操纵频繁、请重试！");
        }
        userWithdrawService.save(userWithdrawEntity);

        return R.ok(orderNumber);
    }


    @ApiOperation("单号查询提现详情")
    @PostMapping(value = "/getUserWithdrawByOrderNumber", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<UserWithdrawEntity> getUserWithdrawByOrderNumber(@RequestBody OrderQUeryVO orderQUeryVO) {
        QueryWrapper<UserWithdrawEntity> userWrap = new QueryWrapper<UserWithdrawEntity>();
        userWrap.eq("withdraw_number", orderQUeryVO.getOrderNumber());
        UserWithdrawEntity userWithdrawEntity = userWithdrawService.getBaseMapper().selectOne(userWrap);

        List<BankCardEntity> bankCardEntityList =  bankCardService.list();
        Map<String,String> carMap = new HashMap<>();
        for (BankCardEntity bankCardEntity : bankCardEntityList){
            carMap.put(bankCardEntity.getBankCode(),bankCardEntity.getBankName());
        }
        if (userWithdrawEntity.getIsCheck() == 0){
            userWithdrawEntity.setIsCheckStr("审核中");
        }else if (userWithdrawEntity.getIsCheck() == 1){
            userWithdrawEntity.setIsCheckStr("审核通过");
        }else if(userWithdrawEntity.getIsCheck() == 2){
            userWithdrawEntity.setIsCheckStr("审核不通过");
        }else if(userWithdrawEntity.getIsCheck() == 3){
            userWithdrawEntity.setIsCheckStr("到账");
        }
        BigDecimal divisor = BigDecimal.valueOf(100);
        BigDecimal dividend = BigDecimal.valueOf( userWithdrawEntity.getBalance());
        BigDecimal balance = dividend.divide(divisor, 2, RoundingMode.HALF_UP);
        userWithdrawEntity.setBalanceStr(balance.toString());

        userWithdrawEntity.setBankDeposit(carMap.get(userWithdrawEntity.getBankDeposit()));

        BigDecimal divisor1 = BigDecimal.valueOf(100);
        BigDecimal dividend1 = BigDecimal.valueOf( userWithdrawEntity.getServiceCharge());
        BigDecimal serviceCharge = dividend1.divide(divisor1, 2, RoundingMode.HALF_UP);
        userWithdrawEntity.setServiceChargeStr(serviceCharge.toString());

        BigDecimal divisor2 = BigDecimal.valueOf(100);
        BigDecimal dividend2 = BigDecimal.valueOf( userWithdrawEntity.getWithdrawAmount());
        BigDecimal withdrawAmount = dividend2.divide(divisor2, 2, RoundingMode.HALF_UP);
        userWithdrawEntity.setWithdrawAmountStr("-"+withdrawAmount.toString());

        String bankNumber = userWithdrawEntity.getBankNumber().substring(userWithdrawEntity.getBankNumber().length()-4,userWithdrawEntity.getBankNumber().length());
        userWithdrawEntity.setBankNumber(bankNumber);

        return R.ok(userWithdrawEntity);
    }

    @ApiOperation("我的钱包")
    @PostMapping(value = "/userPackList", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<PageUtils<UserWithdrawEntity>> userPackList(@RequestBody UserPackVO userPackVO, @RequestHeader("token") String token) {
        LoginUser loginUser = redisService.getLoginValueByToken(token);
        QueryWrapper<UserWithdrawEntity> userWrap = new QueryWrapper<UserWithdrawEntity>();
        userWrap.eq("user_id", loginUser.getId());
        //审核通过
        userWrap.eq("is_check", 1);
        if (!StringUtils.isBlank(userPackVO.getType())){
            userWrap.eq("type", userPackVO.getType());
        }
        if (!StringUtils.isBlank(userPackVO.getEndTime())){
            userWrap.le("update_time", userPackVO.getEndTime()+" 23:59:59");
        }
        userWrap.orderByDesc("id");
        IPage<UserWithdrawEntity> page = new Page<>(userPackVO.getPageNum(), userPackVO.getPageSize());
        page = userWithdrawService.getBaseMapper().selectPage(page, userWrap);
        for (UserWithdrawEntity userWithdrawEntity :page.getRecords()){
            BigDecimal divisor = BigDecimal.valueOf(100);
            BigDecimal dividend = BigDecimal.valueOf( userWithdrawEntity.getBalance());
            BigDecimal price = dividend.divide(divisor, 2, RoundingMode.HALF_UP);
            userWithdrawEntity.setBalanceStr(price.toString());

            BigDecimal dividend1 = BigDecimal.valueOf( userWithdrawEntity.getServiceCharge());
            BigDecimal price1 = dividend1.divide(divisor, 2, RoundingMode.HALF_UP);
            userWithdrawEntity.setServiceChargeStr(price1.toString());

            BigDecimal dividend2 = BigDecimal.valueOf( userWithdrawEntity.getWithdrawAmount());
            BigDecimal price2 = dividend2.divide(divisor, 2, RoundingMode.HALF_UP);
            if(userWithdrawEntity.getType() ==2 ){
                userWithdrawEntity.setWithdrawAmountStr("-"+price2.toString());
            }else{
                userWithdrawEntity.setWithdrawAmountStr(price2.toString());
            }
            userWithdrawEntity.setUrl(requestUrl+"static/userpack/"+userWithdrawEntity.getType()+".png");
        }
        return R.ok(new PageUtils<>(page));
    }

}
